package dao

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"zhongxc.cc/mall-common/msdb"
	"zhongxc.cc/mall-common/msdb/gorms"
	"zhongxc.cc/mall-product/internal/model"
)

type PmsSkuInfoDao struct {
	conn *gorms.GormConn
}

func NewPmsSkuInfoDao(db *msdb.MsDB) *PmsSkuInfoDao {
	return &PmsSkuInfoDao{
		conn: gorms.New(db.Conn),
	}
}

func (p *PmsSkuInfoDao) FindById(ctx context.Context, skuId int64) (pmsSkuInfo *model.PmsSkuInfo, err error) {
	session := p.conn.Session(ctx)
	err = session.Model(&model.PmsSkuInfo{}).
		Where("sku_id=?", skuId).
		Limit(1).
		Take(&pmsSkuInfo).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		// 其他异常处理
		return nil, err
	}
	return pmsSkuInfo, nil
}

func (p *PmsSkuInfoDao) Save(ctx context.Context, skuInfo *model.PmsSkuInfo) error {
	session := p.conn.Session(ctx)
	err := session.Save(skuInfo).Error
	return err
}

func (p *PmsSkuInfoDao) UpdateSaleCount(ctx context.Context, skuId int64, saleCount int64) error {
	session := p.conn.Session(ctx)
	err := session.Exec("UPDATE pms_sku_info SET `sale_count`=? WHERE `sku_id`=?", saleCount, skuId).Error
	return err
}
